package stuSystem.dao.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import stuSystem.dao.StandardDao;
import stuSystem.entity.Standard;

public class StandardDaoImpl extends HibernateDaoSupport implements StandardDao {

	@Override
	public List<Standard> getInfoByKeys(final String text,final int pageNum,final int pageSize) {
		return getHibernateTemplate().execute(new HibernateCallback<List<Standard>>() {

			@Override
			public List<Standard> doInHibernate(Session session)
					throws HibernateException, SQLException {
				String hql = "from Standard where 1=1 ";
				Map<String,Object> list = new HashMap<String, Object>();
				if(text != null && !text.isEmpty()){
					hql += "and stdNum like :stdNum or zhname like :zhname";
					list.put("stdNum", "%"+text+"%");
					list.put("zhname", "%"+text+"%");
				}
				return session.createQuery(hql)
						.setProperties(list)
						.setFirstResult((pageNum-1)*pageSize)
						.setMaxResults(pageSize)
						.list();
			}
		});
	}

	@Override
	public Standard checkExists(String std_num) {
		List<Standard> list = (List<Standard>) getHibernateTemplate().find("from Standard where stdNum = ?",std_num);
		return list.size()==0?null:list.get(0);
	}

	@Override
	public Standard fetchById(int id) {
		return getHibernateTemplate().get(Standard.class, id);
	}

	@Override
	public int getRows(String keys) {
		List<Number> list = (List<Number>) getHibernateTemplate().find("select count(s.id) from Standard s where zhname like ? or stdNum like ? ","%"+keys+"%","%"+keys+"%");
		return list.size()==0?0:list.get(0).intValue();
	}

	@Override
	public void add(Standard standard) {
		getHibernateTemplate().save(standard);
	}

	@Override
	public void update(Standard standard) {
		getHibernateTemplate().update(standard);
	}

	@Override
	public void delete(int id) {
		getHibernateTemplate().delete(getHibernateTemplate().get(Standard.class, id));
	}
	
	public static void main(String[] args) {
		ApplicationContext atx = new ClassPathXmlApplicationContext("beans.xml");
		StandardDao dao = (StandardDao) atx.getBean("standardDao");
		System.out.println(dao.getRows(""));
	}

}
